//
//  ChatViewController.swift
//  SwiftIM
//
//  Created by WuZhijian on 14/12/6.
//  Copyright (c) 2014年 com.liveln. im. All rights reserved.
//

import UIKit

class ChatViewController: UITableViewController,MessageDL {
    @IBOutlet weak var send: UIBarButtonItem!

    @IBOutlet weak var msg: UITextField!
    
    //当前选择聊天的好友昵称
    var toBuddyName = ""
    
    //聊天消息
    var msgList = [WXMessage]()
    
    //总代理
    func zdl() -> AppDelegate {
        return UIApplication.sharedApplication().delegate as AppDelegate
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        //接管消息代理
        zdl().xxdl = self
    }
    
    //发送正在输入状态
    @IBAction func composing(sender: UITextField) {
        //构建xml消息格式
        
        var xmlMessage = DDXMLElement.elementWithName("message") as DDXMLElement
        //增加属性
        xmlMessage.addAttributeWithName("type", stringValue: "chat")
        xmlMessage.addAttributeWithName("to", stringValue: toBuddyName)
        xmlMessage.addAttributeWithName("from", stringValue: NSUserDefaults.standardUserDefaults().stringForKey("weixinID"))
        
        //构建正在输入的状态
        var composing :DDXMLElement = DDXMLElement.elementWithName("composing") as DDXMLElement
        composing.addAttributeWithName("xmlns", stringValue: "http://jabber.org/protocol/chatstates")
        
        
        //把消息节点插入正文
        xmlMessage.addChild(composing)
        
        //发送消息
        zdl().xs?.sendElement(xmlMessage)

    }
    
    //发送消息
    @IBAction func send(sender: UIBarButtonItem) {
        //获取消息文本
        let msgStr = msg.text
        if !msgStr.isEmpty
        {
            //构建xml消息格式
            
            var xmlMessage = DDXMLElement.elementWithName("message") as DDXMLElement
            //增加属性
            xmlMessage.addAttributeWithName("type", stringValue: "chat")
            xmlMessage.addAttributeWithName("to", stringValue: toBuddyName)
            xmlMessage.addAttributeWithName("from", stringValue: NSUserDefaults.standardUserDefaults().stringForKey("weixinID"))
            
            var body :DDXMLElement = DDXMLElement.elementWithName("body") as DDXMLElement
            body.setStringValue(msgStr)
            
            //把消息节点插入正文
            xmlMessage.addChild(body)
            
            //发送消息
            zdl().xs?.sendElement(xmlMessage)
            
            //清空输入框
            msg.text = ""
            
            //保存自己的消息
            var msgEs = WXMessage()
            msgEs.isMe = true
            msgEs.body = msgStr
            
            //加入到聊天记录
            msgList.append(msgEs)
            
            //刷新表格
            self.tableView.reloadData()
        }
    }
    
    //收到离线或未读消息
    func newMessage(msg: WXMessage) {
        //对方正在输入
        if msg.isComposing
        {
            self.navigationItem.title =  "正在输入"
        }
        //如果有消息正文
        else if (msg.body != "")
        {
             println(msg.body)
            //现实聊天的对象
            self.navigationItem.title =  toBuddyName
            
            msgList.append(msg)
            
            //刷新表格
            self.tableView.reloadData()
        }
        
       
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Potentially incomplete method implementation.
        // Return the number of sections.
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete method implementation.
        // Return the number of rows in the section.
        return msgList.count
    }

    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("messageListCell", forIndexPath: indexPath) as UITableViewCell

        // Configure the cell...
        let msgText = msgList[indexPath.row]
        
        //显示消息作者
        if(msgList[indexPath.row].isMe){
            cell.textLabel?.textAlignment = .Right
            cell.textLabel?.textColor = UIColor.greenColor()
            cell.textLabel?.text = msgText.body
        }
        else
        {
            cell.textLabel?.textColor = UIColor.orangeColor()
            cell.textLabel?.textAlignment = .Left
            cell.textLabel?.text = msgText.body
        }
        
        return cell
    }
    

    /*
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return NO if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            // Delete the row from the data source
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        } else if editingStyle == .Insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return NO if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using [segue destinationViewController].
        // Pass the selected object to the new view controller.
    }
    */

}
